import requests
from faker import Faker
from settings import sql_settings
from tools.my_sql import MyMySQL
from tools.global_data import GlobalData



def get_new_phone():
    # 伪造一个phone，判断是否在数据库已有用户中，如果不在则关闭数据库，返回phone
    faker = Faker("zh_CN")
    mmysql = MyMySQL(**sql_settings)
    while True:
        new_phone = faker.phone_number()
        # 数据库查询是否注册过，count=0
        count = mmysql.get_count_from_database(f'SELECT * FROM tz_user WHERE user_mobile={new_phone}')
        if count == 0:
            print("手机号未注册，可以使用")
            break
    mmysql.close()
    # 设置phone为全局变量，供后面的接口使用
    setattr(GlobalData, "new_phone", new_phone)
    return new_phone

# 1.获取验证码接口
phone = get_new_phone()
url = "http://mall.lemonban.com:8107/user/sendRegisterSms"
req_data = {"mobile": f"{phone}"}
resp = requests.request("put", url, json=req_data)

# 2.数据库查询验证码
# "SELECT mobile_code FROM tz_sms_log WHERE user_phone=17762450607 ORDER BY rec_date DESC LIMIT 1;
mmysql = MyMySQL(**sql_settings)
sql = f"SELECT mobile_code FROM tz_sms_log WHERE user_phone={phone} ORDER BY rec_date DESC LIMIT 1"
mobile_code_dict = mmysql.get_result_from_database(sql)

# 3.检验验证码
url = "http://mall.lemonban.com:8107/user/checkRegisterSms"
req_data = {"mobile": phone,
            "validCode": mobile_code_dict[0].get("mobile_code")}
resp = requests.request("put", url, json=req_data)

# 4.注册
url = "http://mall.lemonban.com:8107/user/registerOrBindUser"
req_data = {"appType": 3,
            "checkRegisterSmsFlag": resp.text,
            "mobile": phone,
            "userName": phone,
            "password": "lemon",
            "registerOrBind": 1,
            "validateType": 1}
resp = requests.request("put", url, json=req_data)
